<template>
  <div class="egg-container">
    <el-table
      ref="multipleTableRef"
      :data="userList"
      row-key="id"
      style="width: 100%"
      v-loading="loading"
      :cell-style="{ whiteSpace: 'nowrap' }"
    >
      <el-table-column
        prop="basicInfo.donorId"
        label="捐赠者编号"
        width="120"
        show-overflow-tooltip
      />
      <el-table-column
        prop="sysUser.userName"
        label="用户名（账号）"
        width="140"
        show-overflow-tooltip
      />
      <el-table-column label="状态" width="100">
        <template #default="{ row }">
          <el-tag v-if="row.sysUser.shzt == 1" type="success">已通过</el-tag>
          <el-tag v-if="row.sysUser.shzt == 0">待审核</el-tag>
          <el-tag v-if="row.sysUser.shzt == 2" type="warning">未通过</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="basicInfo.eggFrozenPrice"
        label="冷冻卵子价格(美元)"
        width="140"
        show-overflow-tooltip
      />
      <el-table-column
        prop="basicInfo.eggFreshPrice"
        label="新鲜卵子价格(美元)"
        width="140"
        show-overflow-tooltip
      />
      <el-table-column label="图片数量" width="140" show-overflow-tooltip>
        <template #default="{ row }">{{ row.photoList.length }}</template>
      </el-table-column>
      <el-table-column label="视频数量" width="140" show-overflow-tooltip>
        <template #default="{ row }">
          {{
            row.basicInfo.videoUrl
              ? row.basicInfo.videoUrl.split(",").length
              : 0
          }}
        </template>
      </el-table-column>
      <el-table-column
        prop="basicInfo.ethnicity"
        label="种族"
        width="140"
        show-overflow-tooltip
      />
      <el-table-column
        prop="basicInfo.isSmoker"
        label="是否吸烟"
        width="80"
        show-overflow-tooltip
      />
      <el-table-column
        prop="basicInfo.personalityDescription"
        label="个人描述"
        min-width="220"
        show-overflow-tooltip
      />
      <el-table-column
        prop="basicInfo.personality"
        label="性格描述"
        min-width="220"
        show-overflow-tooltip
      />
      <el-table-column
        prop="basicInfo.bestSkill"
        label="特长"
        width="120"
        show-overflow-tooltip
      />
      <el-table-column
        prop="basicInfo.careerGoal"
        label="事业目标"
        width="120"
        show-overflow-tooltip
      />
      <el-table-column
        prop="basicInfo.reasonForDonation"
        label="捐赠原因"
        min-width="220"
        show-overflow-tooltip
      />
      <el-table-column
        prop="basicInfo.dateOfBirth"
        label="出生日期"
        width="110"
        show-overflow-tooltip
      />
      <el-table-column
        prop="basicInfo.heightInCm"
        label="身高(cm)"
        width="90"
        show-overflow-tooltip
      />
      <el-table-column
        prop="basicInfo.weightInKg"
        label="体重(kg)"
        width="90"
        show-overflow-tooltip
      />
      <el-table-column
        prop="basicInfo.bloodType"
        label="血型"
        width="80"
        show-overflow-tooltip
      />
      <el-table-column
        prop="basicInfo.eyeColor"
        label="瞳色"
        width="80"
        show-overflow-tooltip
      />
      <el-table-column
        prop="basicInfo.hairColor"
        label="发色"
        width="80"
        show-overflow-tooltip
      />
      <el-table-column
        prop="basicInfo.skinColor"
        label="肤色"
        width="80"
        show-overflow-tooltip
      />
      <el-table-column
        prop="basicInfo.bodyStructure"
        label="体型结构"
        width="110"
        show-overflow-tooltip
      />
      <el-table-column
        prop="basicInfo.fathersEthnicity"
        label="父亲种族"
        width="130"
        show-overflow-tooltip
      />
      <el-table-column
        prop="basicInfo.mothersEthnicity"
        label="母亲种族"
        width="130"
        show-overflow-tooltip
      />
      <el-table-column
        prop="basicInfo.bodyType"
        label="体型"
        width="100"
        show-overflow-tooltip
      />
      <el-table-column
        prop="basicInfo.donorCode"
        label="捐赠者编号"
        width="120"
        show-overflow-tooltip
      />

      <el-table-column
        prop="medicalInfo.menstrualRegular"
        label="月经规律"
        width="100"
        show-overflow-tooltip
      />
      <el-table-column
        prop="medicalInfo.everPregnant"
        label="曾怀孕"
        width="90"
        show-overflow-tooltip
      />
      <el-table-column
        prop="medicalInfo.everHadSti"
        label="曾患性病"
        width="90"
        show-overflow-tooltip
      />
      <el-table-column
        prop="medicalInfo.everTakenOtherMedications"
        label="曾服其他药物"
        width="120"
        show-overflow-tooltip
      />
      <el-table-column
        prop="medicalInfo.currentlyUnderMedicalTreatment"
        label="正接受医疗"
        width="120"
        show-overflow-tooltip
      />
      <el-table-column
        prop="medicalInfo.everHadSurgeryOrHospitalized"
        label="曾手术/住院"
        width="120"
        show-overflow-tooltip
      />
      <el-table-column
        prop="medicalInfo.everHadAllergies"
        label="曾过敏"
        width="100"
        show-overflow-tooltip
      />
      <el-table-column
        prop="medicalInfo.everHadMentalHealthConsultation"
        label="曾心理就诊"
        width="130"
        show-overflow-tooltip
      />
      <el-table-column
        prop="medicalInfo.everLivedOrVisitedEurope"
        label="曾旅居欧洲"
        width="150"
        show-overflow-tooltip
      />
      <el-table-column
        prop="medicalInfo.healthStatus"
        label="健康状况"
        width="100"
        show-overflow-tooltip
      />
      <el-table-column
        prop="medicalInfo.hasChildren"
        label="已有子女"
        width="90"
        show-overflow-tooltip
      />
      <el-table-column
        prop="medicalInfo.contraceptionMethod"
        label="避孕方式"
        width="120"
        show-overflow-tooltip
      />
      <el-table-column
        prop="medicalInfo.isUnderStdTreatment"
        label="性病治疗中"
        width="120"
        show-overflow-tooltip
      />
      <el-table-column
        prop="medicalInfo.reasonToBeEggDonor"
        label="捐卵原因"
        min-width="200"
        show-overflow-tooltip
      />
      <el-table-column
        prop="medicalInfo.favoriteFood"
        label="最爱食物"
        width="100"
        show-overflow-tooltip
      />
      <el-table-column
        prop="medicalInfo.favoriteSport"
        label="最爱运动"
        width="100"
        show-overflow-tooltip
      />
      <el-table-column
        prop="medicalInfo.specialTalentsSkills"
        label="特殊才能"
        min-width="200"
        show-overflow-tooltip
      />
      <el-table-column
        prop="medicalInfo.lifeGoalAmbition"
        label="人生目标"
        min-width="200"
        show-overflow-tooltip
      />
      <el-table-column
        prop="medicalInfo.isAdopted"
        label="是否收养子女"
        width="80"
        show-overflow-tooltip
      />

      <el-table-column fixed="right" label="操作" min-width="860">
        <template #default="{ row }">
          <el-button
            link
            type="primary"
            size="small"
            plain
            @click="reviewDonor(row)"
          >
            审核
          </el-button>
          <el-button
            link
            type="primary"
            size="small"
            plain
            @click="addSetState(row)"
          >
            捐赠状态
          </el-button>
          <el-button
            link
            type="primary"
            size="small"
            plain
            @click="addSetPrice(row.basicInfo.donorId)"
          >
            定价
          </el-button>
          <el-button
            link
            type="primary"
            size="small"
            plain
            @click="setNumber(row)"
          >
            冷冻卵子数量
          </el-button>
          <el-button
            link
            type="primary"
            size="small"
            plain
            @click="setProfile(row)"
          >
            个人简介
          </el-button>
          <el-button
            link
            type="primary"
            size="small"
            plain
            @click="addSetImg(row)"
          >
            图片
          </el-button>

          <el-button
            link
            type="primary"
            size="small"
            plain
            @click="uploadXVisiable(row)"
          >
            形象图片 <span v-if="havePhoto(row, '个人形象照')">(OK)</span>
          </el-button>
          <el-button
            link
            type="primary"
            size="small"
            plain
            @click="uploadSVisiable(row)"
          >
            缩略图 <span v-if="havePhoto(row, '缩略图')">(OK)</span>
          </el-button>
          <el-button
            link
            type="primary"
            size="small"
            plain
            @click="addSetVideo(row)"
          >
            视频
          </el-button>
          <el-button
            link
            type="primary"
            size="small"
            plain
            @click="addSetGene(row)"
          >
            基因报告
          </el-button>
          <el-button
            link
            type="primary"
            size="small"
            plain
            @click="addSetImgEdit(row)"
          >
            附件管理
          </el-button>
          <el-button link type="primary" size="small" plain @click="edit(row)">
            编辑
          </el-button>
          <el-button
            link
            type="primary"
            size="small"
            plain
            @click="todelete(row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <reviewEggDonors
      v-if="shVisiable"
      :donorId="formState.basicInfo.donorId"
      :visiable="shVisiable"
      @closeDialog="closeShDialog"
    />

    <el-dialog
      v-model="stateCenterDialogVisible"
      title="设置捐赠状态"
      width="500"
      center
      destroy-on-close
    >
      <div class="container">
        <div class="item">
          <span>捐赠状态：</span>
          <el-radio-group v-model="radio">
            <el-radio :value="0">捐赠就绪</el-radio>
            <el-radio :value="1">停止捐赠</el-radio>
            <el-radio :value="2">捐赠中</el-radio>
          </el-radio-group>
        </div>
      </div>
      <template #footer>
        <el-button @click="stateCenterDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitSetState">确定</el-button>
      </template>
    </el-dialog>

    <el-dialog
      v-model="centerDialogVisible"
      title="定价"
      width="500"
      center
      destroy-on-close
    >
      <div class="container">
        <div class="item">
          <span>新鲜卵子价格：</span>
          <el-input
            v-model="centerDialog.eggFreshPrice"
            style="width: 240px"
            placeholder="请填写新鲜卵子价格"
            clearable
          />
        </div>
        <div class="item">
          <span>冷冻卵子价格：</span>
          <el-input
            v-model="centerDialog.eggFrozenPrice"
            style="width: 240px"
            placeholder="请填写冷冻卵子价格"
            clearable
          />
        </div>
      </div>
      <template #footer>
        <el-button @click="centerDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitSetPrice">确定</el-button>
      </template>
    </el-dialog>

    <el-dialog
      v-model="numberCenterDialogVisible"
      title="冷冻卵子数量"
      width="500"
      center
      destroy-on-close
    >
      <div class="container">
        <div class="item">
          <span>冷冻卵子数量：</span>
          <el-input-number
            v-model="num"
            :min="1"
            :max="10"
            @change="handleChange"
          />
        </div>
      </div>
      <template #footer>
        <el-button @click="numberCenterDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitSetNumber">确定</el-button>
      </template>
    </el-dialog>

    <el-dialog
      v-model="profileCenterDialogVisible"
      title="设置个人简介"
      width="500"
      center
      destroy-on-close
    >
      <el-input
        v-model="textarea"
        type="textarea"
        :rows="8"
        style="width: 100%"
        placeholder="个人简介"
      />
      <template #footer>
        <el-button @click="profileCenterDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitSetProfile">确定</el-button>
      </template>
    </el-dialog>

    <el-dialog
      v-model="imgCenterDialogVisible"
      title="上传图片"
      width="820"
      center
      destroy-on-close
    >
      <el-form-item label="图片上传">
        <el-upload
          v-model:file-list="pfileList"
          :action="uploadUrl"
          :headers="headers"
          list-type="picture-card"
          multiple
          :auto-upload="false"
          accept="image/*"
          :on-exceed="handleExceed"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <div class="el-upload__tip">
        仅支持 jpeg,jpg,png,gif 且不超过 10MB（1：儿时照 2：艺术照 3：生活照）
      </div>
      <template #footer>
        <el-button @click="imgCenterDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitUpload">确定</el-button>
      </template>
    </el-dialog>

    <el-dialog
      v-model="imgCenterDialogVisibleEdit"
      title="图片修改"
      width="820"
      center
      destroy-on-close
    >
      <el-form-item label="图片修改">
        <el-upload
          v-model:file-list="pfileListEdit"
          :action="uploadUrl"
          :headers="headers"
          list-type="picture-card"
          multiple
          :auto-upload="false"
          accept="image/*"
          :on-exceed="handleExceed"
        >
          <el-icon v-if="false"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <template #footer>
        <el-button @click="imgCenterDialogVisibleEdit = false">取消</el-button>
        <el-button type="primary" @click="submitUploadEdit">确定</el-button>
      </template>
    </el-dialog>

    <Suspense>
      <template #default>
        <rightPhoto
          v-if="xVisiable"
          :donorId="formState.basicInfo.donorId"
          :visiable="xVisiable"
          @closeDialog="closeDialog"
        />
      </template>
      <template #fallback>
        <div style="text-align: center; padding: 20px">加载中...</div>
      </template>
    </Suspense>

    <Suspense>
      <template #default>
        <rightPhotos
          v-if="sVisiable"
          :userName="formState.sysUser.userName"
          :donorId="formState.basicInfo.donorId"
          :visiable="sVisiable"
          @closeDialog="closeDialogs"
        />
      </template>
      <template #fallback>
        <div style="text-align: center; padding: 20px">加载中...</div>
      </template>
    </Suspense>

    <el-dialog
      v-model="videoCenterDialogVisible"
      title="上传视频"
      width="500"
      center
      destroy-on-close
    >
      <el-form-item label="视频上传">
        <el-upload
          class="video-uploader"
          :action="uploadUrlVideo"
          :headers="headers"
          multiple
          :limit="5"
          v-model:file-list="videoList"
          accept="video/mp4"
          :auto-upload="false"
          :before-upload="beforeUploadVideo"
          :on-progress="uploadVideoProcess"
          :on-exceed="handleExceedVideo"
          :on-remove="handleRemoveVideo"
        >
          <el-icon v-if="!uploading" class="avatar-uploader-icon"
            ><Plus
          /></el-icon>
          <el-progress
            v-if="uploading"
            type="circle"
            :percentage="uploadPercent"
          />
        </el-upload>
        <div class="el-upload__tip">最多上传 5 个视频，单个不超过 50MB</div>
      </el-form-item>
      <template #footer>
        <el-button @click="videoCenterDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitUploadVideo">确定</el-button>
      </template>
    </el-dialog>

    <el-dialog
      v-model="geneCenterDialogVisible"
      title="上传基因报告"
      width="500"
      center
      destroy-on-close
    >
      <el-form-item label="基因报告">
        <el-upload
          ref="uploadPdfRef"
          class="upload-demo"
          drag
          :auto-upload="false"
          :action="uploadPdfImgUrl"
          :headers="headers"
          :before-upload="handleBeforeUpload"
          :on-remove="handleRemove"
          v-model:file-list="fileList"
          accept=".jpg,.jpeg,.png,.gif,.pdf"
        >
          <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
          <div class="el-upload__text">
            将文件拖到此处，或 <em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              仅支持 jpg/png/gif/pdf，且不超过 10MB
            </div>
          </template>
        </el-upload>
      </el-form-item>
      <template #footer>
        <el-button @click="geneCenterDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitPdf">确定</el-button>
      </template>
    </el-dialog>

    <el-dialog
      v-model="delCenterDialogVisible"
      title="删除捐卵者信息"
      width="500"
      center
      destroy-on-close
    >
      <div><strong>您确定要删除捐卵者信息吗？</strong></div>
      <template #footer>
        <el-button @click="delCenterDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="deleteRows">确定</el-button>
      </template>
    </el-dialog>

    <div class="navigation">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :current-page="queryParams.pageNum"
        :page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script lang="ts" setup>
/**
 *  全 Element Plus 版本（已删除所有模板注释）
 *  1. 所有 ant-design-vue 组件已替换
 *  2. 使用 Suspense 懒加载弹窗子组件
 *  3. 其余业务逻辑与原文件保持一致
 */
import {
  ref,
  reactive,
  onMounted,
  toRaw,
  watch,
  defineAsyncComponent,
} from "vue";
import type { TableInstance } from "element-plus";
import { ElMessage as message } from "element-plus";
import { Plus, UploadFilled } from "@element-plus/icons-vue";

import {
  deleteInfo,
  listEgg,
  setPrice,
  updateFileInfo,
  updatePhoto,
} from "@/api/business/egg";
import { uploadFiles } from "@/api/business/upload";
import { getToken } from "@/utils/auth";
import { useRouter } from "vue-router";

const rightPhoto = defineAsyncComponent(
  () => import("./components/rightPhoto.vue")
);
const rightPhotos = defineAsyncComponent(
  () => import("./components/rightPhotos.vue")
);
const reviewEggDonors = defineAsyncComponent(
  () => import("./components/reviewEggDonors.vue")
);

const router = useRouter();

/* ====== 响应式变量 ====== */
const multipleTableRef = ref<TableInstance>();
const loading = ref(true);
const userList = ref<any[]>([]);
const total = ref(0);
const rowId = ref();
const donorId = ref("");

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  userName: "",
  ethnicity: "",
  descValue: "desc",
});

/* ====== 弹窗显隐 ====== */
const shVisiable = ref(false);
const xVisiable = ref(false);
const sVisiable = ref(false);
const stateCenterDialogVisible = ref(false);
const centerDialogVisible = ref(false);
const numberCenterDialogVisible = ref(false);
const profileCenterDialogVisible = ref(false);
const imgCenterDialogVisible = ref(false);
const imgCenterDialogVisibleEdit = ref(false);
const videoCenterDialogVisible = ref(false);
const geneCenterDialogVisible = ref(false);
const delCenterDialogVisible = ref(false);

/* ====== 表单 & 上传 ====== */
const formState = reactive<any>({
  sysUser: { userName: "" },
  basicInfo: { donorId: "", videoUrl: "", geneReport: "" },
  medicalInfo: {},
  photoList: [],
});
const radio = ref(0);
const centerDialog = ref({ eggFrozenPrice: "", eggFreshPrice: "" });
const num = ref(1);
const textarea = ref("");

const uploadUrl = ref("");
const uploadUrlVideo = ref("");
const uploadPdfImgUrl = ref("");
const headers = { Authorization: "Bearer " + getToken() };
const pfileList = ref<any[]>([]);
const pfileListEdit = ref<any[]>([]);
const fileList = ref<any[]>([]);
const videoList = ref<any[]>([]);
const uploading = ref(false);
const uploadPercent = ref(0);
const photoList = ref<string[]>([]);

/* ====== 业务方法 ====== */
const getList = () => {
  loading.value = true;
  listEgg(queryParams).then((res: any) => {
    loading.value = false;
    userList.value = res.rows;
    total.value = res.total;
  });
};
defineExpose({ search });
function search(listQuery: any) {
  loading.value = true;
  listEgg(listQuery).then((res: any) => {
    loading.value = false;
    userList.value = res.rows;
    total.value = res.total;
  });
}
function havePhoto(row, type) {
  return row.photoList.some((data) => data.photoType === type);
}
const handleSizeChange = (val: number) => {
  queryParams.pageSize = val;
  getList();
};
const handleCurrentChange = (val: number) => {
  queryParams.pageNum = val;
  getList();
};

const reviewDonor = (row: any) => {
  Object.assign(formState, toRaw(row));
  shVisiable.value = true;
};
const closeShDialog = () => {
  shVisiable.value = false;
  getList();
};

const addSetState = (id: any) => {
  rowId.value = id;
  stateCenterDialogVisible.value = true;
};
const submitSetState = () => {
  setPrice({ donorId: rowId.value, ...centerDialog.value }).then(() => {
    message.success("设置成功");
    stateCenterDialogVisible.value = false;
    getList();
  });
};

const addSetPrice = (id: any) => {
  rowId.value = id;
  centerDialogVisible.value = true;
};
const submitSetPrice = () => {
  setPrice({ donorId: rowId.value, ...centerDialog.value }).then(() => {
    message.success("设置成功");
    centerDialogVisible.value = false;
    getList();
  });
};

const setNumber = (id: any) => {
  rowId.value = id;
  numberCenterDialogVisible.value = true;
};
const submitSetNumber = () => {
  setPrice({ donorId: rowId.value, frozenNum: num.value }).then(() => {
    message.success("设置成功");
    numberCenterDialogVisible.value = false;
    getList();
  });
};

const setProfile = (id: any) => {
  rowId.value = id;
  profileCenterDialogVisible.value = true;
};
const submitSetProfile = () => {
  message.success("设置成功");
  profileCenterDialogVisible.value = false;
};

const addSetImg = (row: any) => {
  Object.assign(formState, toRaw(row));
  pfileList.value = [];
  imgCenterDialogVisible.value = true;
};
const uploadXVisiable = (row: any) => {
  Object.assign(formState, toRaw(row));
  xVisiable.value = true;
};
const closeDialog = () => {
  xVisiable.value = false;
};
const uploadSVisiable = (row: any) => {
  Object.assign(formState, toRaw(row));
  sVisiable.value = true;
};
const closeDialogs = () => {
  sVisiable.value = false;
};

const addSetImgEdit = (row: any) => {
  Object.assign(formState, toRaw(row));
  pfileListEdit.value = row.photoList.map((item: any) => ({
    url: item.photoUrl,
    ...item,
  }));
  imgCenterDialogVisibleEdit.value = true;
};
const submitUploadEdit = async () => {
  const queryUrl = pfileListEdit.value.map((item: any) => item.url);
  const query = {
    basicId: formState.basicInfo.donorId,
    photoUrls: queryUrl.join(","),
  };
  const res = await updatePhoto(query);
  if (res.code === 200) {
    message.success("更新成功");
    getList();
    imgCenterDialogVisibleEdit.value = false;
  } else {
    message.error("更新失败");
  }
};

const addSetVideo = (row: any) => {
  Object.assign(formState, toRaw(row));
  videoCenterDialogVisible.value = true;
};
const addSetGene = (row: any) => {
  Object.assign(formState, toRaw(row));
  geneCenterDialogVisible.value = true;
};
const edit = (row: any) =>
  router.push({
    path: "/businessEgg/addEgg",
    query: { basicId: row.basicInfo.donorId },
  });
const todelete = (row: any) => {
  delCenterDialogVisible.value = true;
  donorId.value = row.basicInfo.donorId;
};
const deleteRows = () => {
  deleteInfo(donorId.value).then((res: any) => {
    if (res.code === 200) {
      message.success("删除成功");
      delCenterDialogVisible.value = false;
      getList();
    } else {
      message.error("删除失败");
    }
  });
};

/* ====== 上传相关 ====== */
const handleChange = (value: number | undefined) => console.log(value);
const handleExceed = () => message.warning("最多上传3张图片");
const beforeUploadVideo = (file: File) => {
  const isVideo = file.type.startsWith("video/");
  const isLt50M = file.size / 1024 / 1024 < 50;
  if (!isVideo) message.error("只能上传视频文件");
  if (!isLt50M) message.error("视频大小不能超过 50MB");
  uploading.value = isVideo && isLt50M;
  uploadPercent.value = 0;
  return isVideo && isLt50M;
};
const uploadVideoProcess = (evt: any) => {
  uploadPercent.value = Math.round(evt.percent);
};
const handleExceedVideo = () => message.warning("最多只能上传 5 个视频");
const handleRemoveVideo = (file: any) => {
  const idx = videoList.value.findIndex((item: any) => item.uid === file.uid);
  if (idx > -1) videoList.value.splice(idx, 1);
};
const handleBeforeUpload = (rawFile: File) => {
  const allowType = [
    "image/jpeg",
    "image/jpg",
    "image/png",
    "image/gif",
    "application/pdf",
  ];
  const isAllowed = allowType.includes(rawFile.type);
  const isLt10M = rawFile.size / 1024 / 1024 < 10;
  if (!isAllowed) message.error("仅支持上传 jpg / png / gif / pdf 文件");
  if (!isLt10M) message.error("文件大小不能超过 10MB");
  return isAllowed && isLt10M;
};
const handleRemove = (file: any) => {
  fileList.value = fileList.value.filter((f: any) => f.uid !== file.uid);
};

/* 上传图片 */
const submitUpload = async () => {
  if (!pfileList.value.length) return message.warning("请先选择图片");
  uploadUrl.value =
      "/business/photo/uploads?username=" + formState.sysUser.userName;
  const formData = new FormData();
  pfileList.value.forEach((file) => formData.append("files", file.raw!));
  const res = await uploadFiles(formData, uploadUrl.value);
  formState.photoUrls = res.urls;
  formState.basicInfo.videoUrl = null;
  formState.basicInfo.geneReport = null;
  updateForm(formState);
  imgCenterDialogVisible.value = false;
};

/* 上传视频 */
const submitUploadVideo = async () => {
  if (!videoList.value.length) return message.warning("请先选择视频");
  uploadUrlVideo.value =
      "/business/photo/uploadVideo?username=" + formState.sysUser.userName;
  const formData = new FormData();
  videoList.value.forEach((file) => formData.append("files", file.raw!));
  const res = await uploadFiles(formData, uploadUrlVideo.value);
  formState.basicInfo.videoUrl = res.urls;
  formState.photoUrls = null;
  updateForm(formState);
  videoCenterDialogVisible.value = false;
};

const submitPdf = async () => {
  if (fileList.value.length === 0) return message.warning("请先选择报告");
  uploadPdfImgUrl.value =
    "/business/photo/upload?type=pdfs&username=" + formState.sysUser.userName;
  const formData = new FormData();
  fileList.value.forEach((file: any) => formData.append("file", file.raw));
  try {
    const res = await uploadFiles(formData, uploadPdfImgUrl.value);
    formState.basicInfo.geneReport = res.url;
    formState.photoUrls = null;
    await updateForm(formState);
    geneCenterDialogVisible.value = false;
  } catch (e) {
    message.error("上传失败");
  }
};

const updateForm = async (form: any) => {
  const res = await updateFileInfo(form);
  if (res.code === 200) {
    message.success("上传成功");
    getList();
  } else {
    message.error("上传失败");
  }
  fileList.value = [];
  pfileList.value = [];
  videoList.value = [];
};

watch(
  () => photoList.value,
  (val) => {
    if (pfileList.value.length > 0 && val.length === pfileList.value.length) {
      try {
        formState.photoUrls = val.join(",");
        updateForm(formState);
        imgCenterDialogVisible.value = false;
      } catch {
        message.error("上传失败");
      }
    }
  },
  { deep: true, immediate: true }
);

onMounted(() => getList());
</script>

<style lang="scss" scoped>
.egg-container {
  height: auto;
}
.containerEdit {
  :deep(.el-upload--picture-card) {
    display: none !important;
  }
}
.navigation {
  width: 600px;
  margin: 50px auto;
}
</style>
